﻿using KBEngine.Common;
using KBEngine.Extension;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KBEngineTool.Forms.Entity
{
    public partial class ConsoleWidget : UserControl, ITelnet
    {
        TelnetConsole _telnetConsole;
        public ConsoleWidget()
        {
            InitializeComponent();

            this.Load += AppInfoWidget_Load;
            m_DGV_allinfo.CellContentClick += M_DGV_allinfo_CellContentClick;
            textBox1.KeyDown += TextBox1_KeyDown;
        }

        private void AppInfoWidget_Load(object sender, EventArgs e)
        {
            KBEngine.Event.registerOut(KBEngine.MachineEvent.OnQueryAllInterfaces, this, nameof(__OnQueryAllInterfaces));
        }

        public void __OnQueryAllInterfaces()
        {
            m_DGV_allinfo.Rows.Clear();
            var clientApp = Operation.Inst.ClientApp;
            foreach (var machineInfo in clientApp.MachineList)
            {
                foreach (var appInfo in clientApp.GetAppInfos(machineInfo.machineID))
                {
                    if (appInfo.consolePort <= 0)
                        continue;
                    int index = m_DGV_allinfo.Rows.Add();
                    var newRow = m_DGV_allinfo.Rows[index];
                    newRow.Cells[0].Value = appInfo.intaddr.ToString();
                    newRow.Cells[1].Value = appInfo.fullname.ToString();
                    newRow.Cells[2].Value = appInfo.componentID.ToString();
                    newRow.Cells[3].Value = "连接到控制台";
                    newRow.Tag = appInfo;
                }
            }
        }
        private void M_DGV_allinfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int index = m_DGV_allinfo.SelectedCells[0].RowIndex;
            var comInfo = (ComponentInfo)m_DGV_allinfo.Rows[index].Tag;
            string title = $"{comInfo.fullname} on {comInfo.intaddr}:{comInfo.consolePort}";

            if (_telnetConsole != null)
                _telnetConsole.Close();
            _telnetConsole = new TelnetConsole(this, comInfo.intaddr, comInfo.consolePort);
            _telnetConsole.Run();
        }

        public void Received(string msg)
        {
            RichTextBox_Txt.AppendText(msg);
        }
        private void TextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.Enter)
            {
                if (_telnetConsole != null)
                    _telnetConsole.SendMsg(textBox1.Text);
                textBox1.Text = string.Empty;
                e.SuppressKeyPress = true;
            }
        }
    }
}
